﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using System.Drawing;
using Silvermoon.Animations;
using System.IO;
using System.Reflection;
using Silvermoon.Images;
using Silvermoon.Visuals;
using Silvermoon.Controls.Classes;
using Silvermoon.OpenGL;
using System.Xml;
using GoogleVoice;
using System.ComponentModel;

namespace GVVVM
{

    public class MainMenu : Window
    {
        //private Calculator calculator;
        //private GridWindow gridWindow;
        private VoiceMailDetail voiceMailDetail;
        private Silvermoon.Controls.PictureBox box;
        private LensView view;
        private Toolbar toolbar;
        //private ExplorerWindow explorer;
        //private StartMenuItem dateItem;
        //int seconds;
        Connection gvconn = new Connection();
        public void showLogin()
        {
            
            this.Enabled = false;
            LoginFrm loginFrm = new LoginFrm();
            System.Windows.Forms.DialogResult result = loginFrm.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                this.Enabled = true;
                gvconn.Login(loginFrm.UserName, loginFrm.Password);                
                

            }
            else return;
        }

        public MainMenu()
            : base()
        {


            gvconn.Login("", "");
            

            
            gvconn.DownloadComplete += new EventHandler(gvconn_DownloadComplete);

            // this windows does not need a toolbar:
            ShowToolbar = false;

            Texture b1 = new Texture();
            //Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream("Demo.Images.RegEdit.png");
            //b1.LoadFromStream(str);

            // Get the background image:
            box = new PictureBox { Margin = new Margin(0) };
            box.Image = new Texture();
            SetBackground("Background.jpg");
            Controls.Add(box);

            int height = StartMenuItem.ItemHeight;
            view = new LensView { Margin = new Margin(0), TextColor = Color.White, LensHeight = 160, ItemHeight = height, Locked = false, KeepLensCentered = true };
            TextColor = Color.White;
            Controls.Add(view);

            int j = 0;
            while ((gvconn.ConnectionStatus == Connection.Status.NotLoggedIn || gvconn.ConnectionStatus == Connection.Status.LoginFailed) && j < 5)
            {
                j++;
                if (gvconn.ConnectionStatus == Connection.Status.LoginFailed) showLogin();
                gvconn.GetInbox();
                //gvconn

            }
            if (!(gvconn.ConnectionStatus == Connection.Status.LoggedIn || gvconn.ConnectionStatus == Connection.Status.CacheOnly)) return;

            UpdateMenu();

            

            // set the lens and the offset to a nice position:
            view.TopOffset = -64;
            view.LensOffset = view.ItemHeight * 1 - 20;

            // add a Tick event handler to actualize the current time:
            // Screen.Tick += new EventHandler<Silvermoon.Core.TimeEventArgs>(OnTick);
            toolbar = new Toolbar();
            Toolbar = toolbar;
            toolbar.LeftButton.Text = "Exit";
            toolbar.LeftButton.Click += (s, e) => { ExitApp(); };
            toolbar.RightButton.Text = "Downloading...";
            toolbar.RightButton.Enabled = false;
            toolbar.RightButton.Click += (s, e) => { UpdateInbox(); };
        }

        void gvconn_DownloadComplete(object sender, EventArgs e)
        {

            if(gvconn.ConnectionStatus == Connection.Status.LoginFailed) showLogin();
            UpdateMenu();
            toolbar.RightButton.Text = "Update";
            toolbar.RightButton.Enabled = true;
        }
        public void UpdateInbox()
        {
            toolbar.RightButton.Text = "Downloading...";
            toolbar.RightButton.Enabled = false;
            gvconn.GetInbox();

        }

        public void UpdateMenu()
        {


            int count;
            if (view.Items.Count > gvconn.MyVoiceMails.Count) count = view.Items.Count;
            else count = gvconn.MyVoiceMails.Count;
            for (int i = 0; i < count; i++)
            {
                if (i < gvconn.MyVoiceMails.Count)
                {
                    StartMenuItem smi;
                    VoiceMail voiceMail = gvconn.MyVoiceMails[i];
                    if (i < view.Items.Count)
                    {
                        smi = (StartMenuItem)view.Items[i];
                        smi.Title = voiceMail.DisplayName;
                        smi.Chunks[0].Details = voiceMail.DisplayStartDateTime.ToString();
                        smi.Chunks[0].Title = voiceMail.DisplayName;
                    }
                    else
                    {
                        smi = new StartMenuItem(voiceMail.DisplayName, voiceMail.DisplayStartDateTime.ToString());
                        smi.Chunks[0].Click += (s, e) => ShowVoicemail((StartMenuDetailChunk)s);
                    }
                    if (i < 10 && !voiceMail.IsDownloaded) voiceMail.Download(gvconn.AuthToken);
                    smi.Chunks[0].VoiceMail = voiceMail;
                    if(i >= view.Items.Count) view.Items.Add(smi);
                    
                }
                else view.Items.Remove(view.Items[i]);
            }

        }
        /// <summary>
        /// Sets the background image.
        /// </summary>
        /// <param name="name">The name of the image to get from resource.</param>
        private void SetBackground(string name)
        {
            string resourcePath = string.Format("GVVVM.Images.{0}", name);
            Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream(resourcePath);
            if (stream == null) throw new SystemException("Resource not found: " + resourcePath);
            box.Image.LoadFromStream(stream);

        }
        

        /// <summary>
        /// To ensure to exit this application we show a dialog to confirm:
        /// </summary>
        private void ExitApp()
        {
            ConfirmDialog dlg = new ConfirmDialog("Exit Application", "Do you really want to quit?");
            dlg.Margin = new Margin(0, null, 0, 0);
            dlg.HideTransition = TransitionMode.SwipeOutToBottom;
            dlg.ShowModal(TransitionMode.SwipeInFromBottom, (s, e) =>
                {
                    if (e.Result == DialogResult.OK) Screen.Close();
                });
        }
        
        void OnWindowHiding(object sender, EventArgs e)
        {
            this.Visible = true;
            this.SendToBack();
            PreLoad();
        }
        
        void ShowVoicemail(StartMenuDetailChunk c)
        {
            if (c.VoiceMail != null)
            {
                voiceMailDetail = new VoiceMailDetail(c.VoiceMail, gvconn);
                voiceMailDetail.Hiding += OnWindowHiding;
                voiceMailDetail.Shown += (s, e) => { this.Visible = false; };

                voiceMailDetail.Show(TransitionMode.ZoomIn);
                voiceMailDetail.Focus();
            }
        }
        public override void Focus()
        {
            view.Focus();
        }

    }
}
